import React, { useState, useEffect } from 'react';
import {
  Card,
  Table,
  Button,
  Form,
  Input,
  Select,
  DatePicker,
  Space,
  Statistic,
  Row,
  Col,
  Tag,
  Modal,
  Descriptions
} from 'antd';
import { SearchOutlined, EyeOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import type { TablePaginationConfig } from 'antd/es/table';
import { getFundDetails } from '@/api/modules/fund';
import type { FundDetailItem, FundDetailsRequest, FundDetailsResponse } from '@/api/modules/fund';
import type { Dayjs } from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;

const FundDetails: React.FC = () => {
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const [data, setData] = useState<FundDetailItem[]>([]);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0
  });
  const [detailVisible, setDetailVisible] = useState(false);
  const [selectedRecord, setSelectedRecord] = useState<FundDetailItem | null>(null);

  // 统计数据
  const [statistics, setStatistics] = useState({
    totalIncome: 0,
    totalExpense: 0,
    transactionCount: 0
  });

  const columns: ColumnsType<FundDetailItem> = [
    {
      title: '交易编号',
      dataIndex: 'transactionId',
      key: 'transactionId',
      width: 120
    },
    {
      title: '交易类型',
      dataIndex: 'type',
      key: 'type',
      width: 100,
      render: (type: string) => (
        <Tag color={type === 'income' ? 'green' : 'red'}>
          {type === 'income' ? '收入' : '支出'}
        </Tag>
      )
    },
    {
      title: '金额',
      dataIndex: 'amount',
      key: 'amount',
      width: 100,
      render: (amount: number) => (
        <span style={{ color: amount > 0 ? '#52c41a' : '#f5222d' }}>
          {amount > 0 ? '+' : ''}{amount.toFixed(2)}
        </span>
      )
    },
    {
      title: '交易方式',
      dataIndex: 'paymentMethod',
      key: 'paymentMethod',
      width: 100
    },
    {
      title: '交易状态',
      dataIndex: 'status',
      key: 'status',
      width: 100,
      render: (status: string) => {
        const statusConfig = {
          success: { color: 'green', text: '成功' },
          pending: { color: 'orange', text: '处理中' },
          failed: { color: 'red', text: '失败' }
        };
        const config = statusConfig[status as keyof typeof statusConfig] || { color: 'default', text: status };
        return <Tag color={config.color}>{config.text}</Tag>;
      }
    },
    {
      title: '交易时间',
      dataIndex: 'transactionTime',
      key: 'transactionTime',
      width: 150,
      render: (time: string) => new Date(time).toLocaleString()
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      ellipsis: true
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      render: (_, record) => (
        <Button
          type="link"
          icon={<EyeOutlined />}
          onClick={() => handleViewDetail(record)}
        >
          详情
        </Button>
      )
    }
  ];

  const loadData = async (params: Omit<FundDetailsRequest, 'page' | 'pageSize'> = {}) => {
    setLoading(true);
    try {
      const response = await getFundDetails({
        page: pagination.current,
        pageSize: pagination.pageSize,
        ...params
      });
      // 响应拦截器已经提取了 data 字段，所以 response 就是 FundDetailsResponse
      const data = response as unknown as FundDetailsResponse;
      setData(data.list || []);
      setPagination(prev => ({
        ...prev,
        total: data.total || 0
      }));
      setStatistics({
        totalIncome: data.statistics?.totalIncome || 0,
        totalExpense: data.statistics?.totalExpense || 0,
        transactionCount: data.statistics?.transactionCount || 0
      });
    } catch (error) {
      console.error('加载资金明细失败:', error);
      // 详细日志
      if (error instanceof Error) {
        console.error('Error details:', error.message);
      } else {
        console.error('Unknown error:', error);
      }
    } finally {
      setLoading(false);
    }
  };

  interface SearchFormValues {
    transactionId?: string;
    type?: 'income' | 'expense';
    status?: 'success' | 'pending' | 'failed';
    dateRange?: [Dayjs, Dayjs];
  }

  const handleSearch = (values: SearchFormValues) => {
    const params: Omit<FundDetailsRequest, 'page' | 'pageSize'> = {};
    if (values.transactionId) {
      params.transactionId = values.transactionId;
    }
    if (values.type) {
      params.type = values.type;
    }
    if (values.status) {
      params.status = values.status;
    }
    if (values.dateRange) {
      params.startTime = values.dateRange[0].format('YYYY-MM-DD');
      params.endTime = values.dateRange[1].format('YYYY-MM-DD');
    }
    loadData(params);
  };

  const handleReset = () => {
    form.resetFields();
    loadData();
  };

  const handleTableChange = (pagination: TablePaginationConfig) => {
    if (pagination.current && pagination.pageSize) {
      setPagination({
        current: pagination.current,
        pageSize: pagination.pageSize,
        total: pagination.total || 0
      });
    }
    loadData();
  };

  const handleViewDetail = (record: FundDetailItem) => {
    setSelectedRecord(record);
    setDetailVisible(true);
  };

  const handleCloseDetail = () => {
    setDetailVisible(false);
    setSelectedRecord(null);
  };

  useEffect(() => {
    loadData();
  }, [pagination.current, pagination.pageSize]);

  return (
    <div>
      <Card>
        {/* 统计信息 */}
        <Row gutter={16} style={{ marginBottom: 24 }}>
          <Col span={8}>
            <Statistic
              title="总收入"
              value={statistics.totalIncome}
              precision={2}
              valueStyle={{ color: '#52c41a' }}
              prefix="¥"
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="总支出"
              value={statistics.totalExpense}
              precision={2}
              valueStyle={{ color: '#f5222d' }}
              prefix="¥"
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="交易笔数"
              value={statistics.transactionCount}
            />
          </Col>
        </Row>

        {/* 查询表单 */}
        <Form
          form={form}
          layout="inline"
          onFinish={handleSearch}
          style={{ marginBottom: 16 }}
        >
          <Form.Item name="transactionId" label="交易编号">
            <Input placeholder="请输入交易编号" />
          </Form.Item>
          <Form.Item name="type" label="交易类型">
            <Select placeholder="请选择交易类型" style={{ width: 120 }}>
              <Option value="income">收入</Option>
              <Option value="expense">支出</Option>
            </Select>
          </Form.Item>
          <Form.Item name="status" label="交易状态">
            <Select placeholder="请选择状态" style={{ width: 120 }}>
              <Option value="success">成功</Option>
              <Option value="pending">处理中</Option>
              <Option value="failed">失败</Option>
            </Select>
          </Form.Item>
          <Form.Item name="dateRange" label="交易时间">
            <RangePicker />
          </Form.Item>
          <Form.Item>
            <Space>
              <Button type="primary" htmlType="submit" icon={<SearchOutlined />}>
                查询
              </Button>
              <Button onClick={handleReset}>重置</Button>
            </Space>
          </Form.Item>
        </Form>

        {/* 数据表格 */}
        <Table
          columns={columns}
          dataSource={data}
          rowKey="transactionId"
          loading={loading}
          pagination={{
            current: pagination.current,
            pageSize: pagination.pageSize,
            total: pagination.total,
            showSizeChanger: true,
            showQuickJumper: true,
            showTotal: (total, range) =>
              `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`
          }}
          onChange={handleTableChange}
          scroll={{ x: 1000 }}
        />
      </Card>

      {/* 交易详情模态框 */}
      <Modal
        title="交易详情"
        open={detailVisible}
        onCancel={handleCloseDetail}
        footer={[
          <Button key="close" onClick={handleCloseDetail}>
            关闭
          </Button>
        ]}
        width={600}
      >
        {selectedRecord && (
          <Descriptions column={1} bordered>
            <Descriptions.Item label="交易编号">{selectedRecord.transactionId}</Descriptions.Item>
            <Descriptions.Item label="交易类型">
              <Tag color={selectedRecord.type === 'income' ? 'green' : 'red'}>
                {selectedRecord.type === 'income' ? '收入' : '支出'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="金额">
              <span style={{ color: selectedRecord.amount > 0 ? '#52c41a' : '#f5222d' }}>
                {selectedRecord.amount > 0 ? '+' : ''}{selectedRecord.amount.toFixed(2)}
              </span>
            </Descriptions.Item>
            <Descriptions.Item label="交易方式">{selectedRecord.paymentMethod}</Descriptions.Item>
            <Descriptions.Item label="交易状态">
              <Tag color={
                selectedRecord.status === 'success' ? 'green' :
                selectedRecord.status === 'pending' ? 'orange' : 'red'
              }>
                {selectedRecord.status === 'success' ? '成功' :
                 selectedRecord.status === 'pending' ? '处理中' : '失败'}
              </Tag>
            </Descriptions.Item>
            <Descriptions.Item label="交易时间">
              {new Date(selectedRecord.transactionTime).toLocaleString()}
            </Descriptions.Item>
            <Descriptions.Item label="备注">{selectedRecord.remark || '无'}</Descriptions.Item>
          </Descriptions>
        )}
      </Modal>
    </div>
  );
};

export default FundDetails;